package com.fxhy.controller;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fxhy.utils.CosUtil;
import com.fxhy.utils.DateUtils;
import com.baby.bean.AgentInviteUserInfo;
import com.baby.bean.UserInfo;
import com.fxhy.bean.AgentUser;
import com.fxhy.bean.IdCardInfo;
import com.fxhy.bean.IdentifiInfo;
import com.fxhy.bean.InviteCodeInfo;
import com.fxhy.bean.LicenceImgInfo;
import com.fxhy.bean.custom.AgentUserCustom;
import com.fxhy.config.IdentifyConfig;
import com.fxhy.contants.Constants;
import com.fxhy.service.AgentLogService;
import com.fxhy.service.AgentRechargeService;
import com.fxhy.service.IdCardInfoService;
import com.fxhy.service.IdentifiInfoService;
import com.fxhy.service.InviteCodeInfoService;
import com.fxhy.service.InviteUserInfoService;
import com.fxhy.service.LicenceImgInfoService;
import com.fxhy.service.UserService;
import com.fxhy.utils.Base64Util;
import com.fxhy.utils.CommonUtils;
import com.fxhy.utils.GsonUtil;
import com.fxhy.utils.JWTUtil;
import com.fxhy.utils.MyPicture;
import com.fxhy.utils.QrCodeUtil;
import com.fxhy.vo.CardAndBankVo;
import com.fxhy.vo.LicenceUserVo;
import com.fxhy.vo.ResponseBodyEntity;
import com.github.pagehelper.PageInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;


@RestController
@Api(value="用户接口")
@RequestMapping("user")
@Slf4j
public class UserApi {
	@Autowired
	private UserService userService;
	
	@Autowired
	private IdentifiInfoService identifiInfoService;
	
	@Autowired
	private IdCardInfoService idCardInfoService;
	
	@Autowired
	private InviteCodeInfoService inviteCodeInfoService;
	
	@Autowired
	private AgentRechargeService agentRechargeService;
	
	@Autowired
	private LicenceImgInfoService licenceImgInfoService;
	
	@Autowired
	private AgentLogService agentLogService;
	
	/**
	 * 获取token
	 * @param username
	 * @param password
	 * @return
	 */
	@ApiOperation("获取token")
	@RequestMapping(value="/getToken/{username}/{password}",method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity getToken(@PathVariable String username,@PathVariable String password){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		responseBodyEntity.setData(JWTUtil.sign(username, password));
		responseBodyEntity.setMsg("获取token");
		responseBodyEntity.setState(Constants.SUCCEED);
		return responseBodyEntity;
	}
	
	/**
	 * 修改用户信息
	 * @return
	 */
	@ApiOperation("修改用户信息")
	@RequestMapping(value="/saveUserInfo",method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity saveUserInfo(AgentUser userInfo,String token){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		if(userInfo.getUserId()!=null) {
			responseBodyEntity.setData(userService.updateUser(userInfo));
			responseBodyEntity.setMsg("修改用户信息成功");
			responseBodyEntity.setState(Constants.SUCCEED);
		}else {
			responseBodyEntity.setMsg("修改用户信息失败,参数用户id缺失");
			responseBodyEntity.setState(Constants.FAILURE);
		}
		responseBodyEntity.setToken(token);
		return responseBodyEntity;
	}
	

	@ApiOperation("修改用户头像")
//	@ApiImplicitParams({
//		@ApiImplicitParam(paramType="query",name="userId",dataType="Integer",required=true,value="用户ID",defaultValue="-1"),
//		@ApiImplicitParam(paramType="query",name="head",dataType="MultipartFile",required=true,value="新头像图片",defaultValue=""),
//		@ApiImplicitParam(paramType="query",name="token",dataType="String",required=true,value="token",defaultValue="")
//		        })
	@RequestMapping(value="updateHead",method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity updateHead(String phoneNum,@RequestParam MultipartFile file, String token, HttpServletResponse response, HttpServletRequest request) throws Exception{
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		AgentUser user = userService.findUserByPhone(phoneNum);
		if(user != null) {
			user = userService.updateHead(user,file);
			
			log.info("新头像：{}",user.getHeadImgUrl());
			
			//记录日志
			agentLogService.saveAgentLog(user,2);
			  
			responseBodyEntity.setData(user);
			responseBodyEntity.setMsg("修改头像成功");
			responseBodyEntity.setState(Constants.SUCCEED);
		}else {
			responseBodyEntity.setMsg("用户未登录!");
			responseBodyEntity.setState(Constants.FAILURE);
		}
		responseBodyEntity.setToken(token);
		return responseBodyEntity;
	}
	
	/**
	 * 修改用户基础信息
	 * @return
	 */
	@ApiOperation("修改用户基础信息")
	@RequestMapping(value="saveAgentInfo",method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity saveAgentInfo(String phoneNum,String nickName,Integer sex,String token){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		if(phoneNum !=null && nickName != null && nickName != "" && sex != null) {
			AgentUser userInfo = userService.findUserByPhone(phoneNum);
			if(userInfo != null && userInfo.getUserId() != null){
				userInfo.setNickName(nickName);
				userInfo.setSex(sex);
				
				//记录日志
				agentLogService.saveAgentLog(userInfo,3);
				
				responseBodyEntity.setData(userService.updateUser(userInfo));
				responseBodyEntity.setMsg("修改用户信息成功");
				responseBodyEntity.setState(Constants.SUCCEED);
			}else{		
				responseBodyEntity.setData("/login");
				responseBodyEntity.setMsg("未发现你的认证信息!为了避免信息泄露!请重新登录!");
				responseBodyEntity.setState(Constants.FAILURE);
				return responseBodyEntity;
			}
		}else {
			responseBodyEntity.setMsg("信息不能为空!修改用户信息失败!");
			responseBodyEntity.setState(Constants.FAILURE);
		}
		responseBodyEntity.setToken(token);
		return responseBodyEntity;
	}
	
	/**
	 * 查找用户信息
	 * @return
	 */
	@ApiOperation("查询用户基础信息")
	@RequestMapping(value="findAgentInfo",method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity findAgentInfo(String phoneNum,String token){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		AgentUser userInfo = userService.findUserByPhone(phoneNum);
		if(userInfo != null && userInfo.getUserId() != null){
			userInfo.setUpdateTime(DateUtils.getNowDate());
			String newToken = JWTUtil.sign(userInfo.getUserId()+"",userInfo.getLastLoginTime());
			userInfo.setUserId(-1);
			userInfo.setHeadImgUrl("data:image/jpeg;base64," + Base64Util.GetBaseStrByImg(userInfo.getHeadImgUrl()));
			
			responseBodyEntity.setData(userInfo);
			responseBodyEntity.setMsg("修改用户信息成功");
			responseBodyEntity.setToken(newToken);
			responseBodyEntity.setState(Constants.SUCCEED);
		}else{		
			responseBodyEntity.setData("/login");
			responseBodyEntity.setMsg("未发现你的认证信息!为了避免信息泄露!请重新登录!");
			responseBodyEntity.setState(Constants.FAILURE);
			return responseBodyEntity;
		}
		return responseBodyEntity;
	}
	
	/**
	 * 生成专属码    base64图片   上传到腾讯云cos
	 * @return
	 * @throws IOException 
	 * @throws URISyntaxException 
	 */
	@ApiOperation("生成-查询专属码")
	@RequestMapping(value="initInviteCode",method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity initInviteCode(String phoneNum,String token) throws URISyntaxException, IOException{
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		AgentUserCustom user = userService.findCustomByPhoneNum(phoneNum);
		if(user == null || user.getUserId() == null || user.getIsIdentifi() <= 0){
			responseBodyEntity.setData("/login");
			responseBodyEntity.setMsg("未发现你的认证信息!为了避免信息泄露!请重新登录!");
			responseBodyEntity.setState(Constants.FAILURE);
			return responseBodyEntity;
		}else{
			List<InviteCodeInfo> list = inviteCodeInfoService.findInviteCodeInfoById(user.getUserId());
			InviteCodeInfo invite =  (list == null || list.size() == 0 ? null : list.get(0));
			if(invite == null || invite.getInviteCode() == null){
				String inviteCode = CommonUtils.getRandomString(6);
				while(inviteCodeInfoService.findCountSameAsInviteCode(inviteCode) != 0){
					inviteCode = CommonUtils.getRandomString(6);
				}
				invite = new InviteCodeInfo();
				invite.setUserId(user.getUserId());
				invite.setInviteCode(inviteCode);
				invite.setStatus(1);
				invite.setCreateTime(DateUtils.getNowDate());
				invite.setCreateUser(user.getNickName());
				
				//生成二维码图片   上传到腾讯云
				Map<String,String> qrCodeMap = QrCodeUtil.getQrImgURLForAgentInvite(user,inviteCode);
				String qrCodeFile = qrCodeMap.get("qrPath");     //本地图片地址
				invite.setInviteImgStr(qrCodeMap.get("qrCode"));                 //二维码字符串
				invite.setInviteImgUrl(CosUtil.putFile(qrCodeFile, "qrInvite")); //二维码腾讯云地址
				invite.setInviteImgUrl1(CosUtil.putFile(MyPicture.setInviteImg(user.getUserId(),user.getCompanyName(),qrCodeFile,1,user.getRoleId()), "invite/img1"));
				invite.setInviteImgUrl2(CosUtil.putFile(MyPicture.setInviteImg(user.getUserId(),user.getCompanyName(),qrCodeFile,2,user.getRoleId()), "invite/img2"));
				invite = inviteCodeInfoService.saveInviteCode(invite);
				
				responseBodyEntity.setMsg("生成专属码成功");
			}else{
				responseBodyEntity.setMsg("存在专属码,正在为你查询。");
			}
			identifiInfoService.initInviteCode(user.getUserId(),invite.getInviteCode());
			user.setInviteCodeInfo(invite);
			user.setInviteCode(invite.getInviteCode());
			
			responseBodyEntity.setData(user);
			responseBodyEntity.setState(Constants.SUCCEED);
		}
		return responseBodyEntity;
	}
	
	
	/**
	 * 20190117  新接口     个体直接认证完成      商铺填写商铺名称
	 * 选择认证类型    生成认证对象  认真完成
	 * @return
	 */
	@ApiOperation("选择认证类型    生成认证对象   认证完成")
	@RequestMapping(value="chooseIdentifyTypeAndFinish",method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity chooseIdentifyTypeAndFinish(String phoneNum,Integer identityType,String searchCode, String token){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		AgentUser user = userService.findUserByPhone(phoneNum);
		if(user != null && user.getUserId() != null && user.getIsIdentifi() == -1){
			if(searchCode != null){
				if(identityType != null){
					IdentifiInfo identify = identifiInfoService.findIdentifiInfoByUserId(user.getUserId());
					if(identify != null && identify.getUserId() != null){
						if(identify.getSearchCode().equals(searchCode)){
							user.setRoleId(identityType);
							
							identify.setSearchCode("");
							identify.setRoleId(identityType);
							
							//如果是个体
							if(identityType == 3){
								user.setIsBindingCard(1);
								user.setIsBindingLicence(1);
								user.setIsBindingBank(1);
								user.setIsIdentifi(user.getRoleId());    //1直接审核通过
								
		   						//身份证
		   						identify.setAddress("身份证暂不需");
								identify.setUserName("身份证暂不需");
								identify.setIdNum("身份证暂不需");
								identify.setIdCardImg1("身份证暂不需");
								identify.setIdCardImg2("身份证暂不需");
		   						
		   						//基础信息
								identify.setCompanyLicenceImg("无");
		   						identify.setCompanyAddress("无");
		   						identify.setCompanyLicenceCode("无");
		   						identify.setCompanyName("无");
		   						identify.setPayeeName("银行卡暂不需");
								identify.setPayeeCardFrom("银行卡暂不需");
								identify.setPayeeCardNum("银行卡暂不需");
								identify.setStatus(1);     //1直接审核通过
								identify.setUpdateTime(DateUtils.getNowDate());
								identify.setUpdateUser(user.getNickName());
								identify.setRechargeRatio(Constants.RechargeRatioLevel1);     //默认0.01
								identify.setRatioByActivity(Constants.RatioByActivityLevel1);     //附加值默认为0
							}
							identifiInfoService.saveIdentifyInfo(identify);
							responseBodyEntity.setData(userService.updateUser(user));
							responseBodyEntity.setMsg("【"+user.getNickName()+"】选择认证类型为: " + identityType);
							responseBodyEntity.setState(Constants.SUCCEED);
						}else{
							responseBodyEntity.setMsg("短信验证码错误!");
							responseBodyEntity.setState(Constants.FAILURE);
							return responseBodyEntity;
						}
					}else{
						responseBodyEntity.setMsg("短信验证码失效!请重新发送短信!");
						responseBodyEntity.setState(Constants.FAILURE);
						return responseBodyEntity;
					}
				}else{
					responseBodyEntity.setMsg("认证类型选择不能为空!");
					responseBodyEntity.setState(Constants.FAILURE);
					return responseBodyEntity;
				}
			}else{
				responseBodyEntity.setMsg("短信验证码不能为空!");
				responseBodyEntity.setState(Constants.FAILURE);
				return responseBodyEntity;
			}
		}else{		
			responseBodyEntity.setData("/login");
			responseBodyEntity.setMsg("未发现你的认证信息!为了避免信息泄露!请重新登录!");
			responseBodyEntity.setState(Constants.FAILURE);
			return responseBodyEntity;
		}
		return responseBodyEntity;
	}
	
	/**
	 * 选择认证类型    生成认证对象
	 * @return
	 */
	@ApiOperation("选择认证类型    生成认证对象")
	@RequestMapping(value="chooseIdentifyType",method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity chooseIdentifyType(String phoneNum,Integer identityType,String searchCode, String token){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		AgentUser user = userService.findUserByPhone(phoneNum);
		if(user != null && user.getUserId() != null && user.getIsIdentifi() == -1){
			if(searchCode != null){
				if(identityType != null){
					IdentifiInfo identify = identifiInfoService.findIdentifiInfoByUserId(user.getUserId());
					if(identify != null && identify.getUserId() != null){
						if(identify.getSearchCode().equals(searchCode)){
							user.setRoleId(identityType);
							
							identify.setSearchCode("");
							identify.setRoleId(identityType);
							identifiInfoService.saveIdentifyInfo(identify);
							
							responseBodyEntity.setData(userService.updateUser(user));
							responseBodyEntity.setMsg("【"+user.getNickName()+"】选择认证类型为: " + identityType);
							responseBodyEntity.setState(Constants.SUCCEED);
						}else{
							responseBodyEntity.setMsg("短信验证码错误!");
							responseBodyEntity.setState(Constants.FAILURE);
							return responseBodyEntity;
						}
					}else{
						responseBodyEntity.setMsg("短信验证码失效!请重新发送短信!");
						responseBodyEntity.setState(Constants.FAILURE);
						return responseBodyEntity;
					}
				}else{
					responseBodyEntity.setMsg("认证类型选择不能为空!");
					responseBodyEntity.setState(Constants.FAILURE);
					return responseBodyEntity;
				}
			}else{
				responseBodyEntity.setMsg("短信验证码不能为空!");
				responseBodyEntity.setState(Constants.FAILURE);
				return responseBodyEntity;
			}
		}else{		
			responseBodyEntity.setData("/login");
			responseBodyEntity.setMsg("未发现你的认证信息!为了避免信息泄露!请重新登录!");
			responseBodyEntity.setState(Constants.FAILURE);
			return responseBodyEntity;
		}
		return responseBodyEntity;
	}
	
	// 此方法是POST请求上传的参数中包含本地图片信息File类型
	@ApiOperation("上传身份证正面的校验")
	@RequestMapping(value="uploadIDcardFile",method= {RequestMethod.GET,RequestMethod.POST})
    public ResponseBodyEntity uploadIDcardFile(String phoneNum,String type, MultipartFile file,String token) throws Exception {
    	ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
    	
    	AgentUser user = userService.findUserByPhone(phoneNum);
    	if(user != null && user.getUserId() != null && user.getIsIdentifi() == -1){
    		CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String rep = null;
            RequestConfig config = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build();
            try {
                HttpPost httppost = new HttpPost("http://v.juhe.cn/certificates/query.php");
                // FileBody封装File类型的参数
                File f = null;
                f=File.createTempFile("tmp", null);
                file.transferTo(f);

                FileBody bin = new FileBody(f);
                f.deleteOnExit();
                StringBody keyBody = new StringBody(IdentifyConfig.KEY, ContentType.TEXT_PLAIN);
                StringBody typeBody = new StringBody(type, ContentType.TEXT_PLAIN);
                HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("pic", bin).addPart("key", keyBody).addPart("cardType", typeBody).build();
                httppost.setEntity(reqEntity);
                httppost.setConfig(config);
                
                response = httpClient.execute(httppost);
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    rep = ConvertStreamToString(resEntity.getContent(), "UTF-8");
                    if(rep != null){
                    	JSONObject jsStr = JSONObject.fromObject(rep);
                    	log.info(jsStr.toString());
                    	if((int)jsStr.get("error_code") == 0){
                    		
                    		
                    		JSONObject result = jsStr.getJSONObject("result");// 找到result的json对象
                    		IdCardInfo card = GsonUtil.fromJson(result.toString(), IdCardInfo.class);
                    		card.setUserId(user.getUserId());
                    		card.setStatus(1);
                    		card.setCreateTime(DateUtils.getNowDate());
                    		card.setCreateUser(user.getNickName());
                    		card.setUpdateTime(DateUtils.getNowDate());
                    		card.setUpdateUser(user.getNickName());
                    		
                    		//上传图片
                    		String fileUrl = CosUtil.uploadFile2Cos(file, "card");
                    		if(fileUrl == null){
                    			responseBodyEntity.setMsg("图片文件上传失败!请稍后再试!");
                    			responseBodyEntity.setState(Constants.FAILURE);
                    			return responseBodyEntity;
                    		}
                    		card.setIdCardImg1(fileUrl);
                    		
                    		//查找是否存在该userId的绑定信息,存在则赋值userId为-1
                    		IdCardInfo c = idCardInfoService.findCardByUserId(user.getUserId());
                    		if(c != null && c.getIdCardInfoId() != null){
                    			c.setUserId(-1);
                    			idCardInfoService.saveIdCardInfo(c);
                    		}
                    		
                    		card = idCardInfoService.saveIdCardInfo(card);
                    		card.setUserId(-1);
                    		responseBodyEntity.setData(card);
    						responseBodyEntity.setMsg("身份证上传成功!");
    						responseBodyEntity.setState(Constants.SUCCEED);
                    	}else{
                    		responseBodyEntity.setMsg(jsStr.getString("reason"));
            				responseBodyEntity.setState(Constants.FAILURE);
            				return responseBodyEntity;
                    	}
                    }else{
                    	responseBodyEntity.setMsg("证件识别失败!请稍后再试!");
        				responseBodyEntity.setState(Constants.FAILURE);
        				return responseBodyEntity;
                    }
                }
                EntityUtils.consume(resEntity);
            }catch(Exception e){
            	responseBodyEntity.setState(Constants.FAILURE);
            }finally {
                response.close();
                httpClient.close();
            }
    	}else{		
			responseBodyEntity.setData(userService.updateUser(user));
			responseBodyEntity.setMsg("你已完成了认证或者登陆失效!请刷新界面!\n若刷新无效!请重新登录!");
			responseBodyEntity.setState(Constants.FAILURE);
			return responseBodyEntity;
		}
        return responseBodyEntity;
    }
	
	@ApiOperation("查询已经录入的身份证信息")
	@RequestMapping(value="findCardRemime",method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity findCardRemime(String phoneNum, String token){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		AgentUser user = userService.findUserByPhone(phoneNum);
		if(user != null && user.getUserId() != null && user.getIsIdentifi() == -1){
			CardAndBankVo vo = new CardAndBankVo();
			
			IdentifiInfo identify = identifiInfoService.findIdentifiInfoByUserId(user.getUserId());
			
			//身份证
			if(user.getIsBindingCard() != 1){
				IdCardInfo card = idCardInfoService.findCardByUserId(user.getUserId());
				if(card != null && card.getIdCardInfoId() != null){
					vo.setUserName(card.getUserName());
					vo.setCardNum(card.getCardNum());
					vo.setCardNum(card.getCardNum());
					vo.setAddress(card.getAddress());
					vo.setIdCardImg1(card.getIdCardImg1());
				}
			}else{
				vo.setUserName(identify.getUserName());
				vo.setCardNum(identify.getIdNum());
				vo.setAddress(identify.getAddress());
				vo.setIdCardImg1(identify.getIdCardImg1());
				
				//银行卡
				vo.setPayeeName(identify.getPayeeName());
				vo.setPayeeCardFrom(identify.getPayeeCardFrom());
				vo.setPayeeCardNum(identify.getPayeeCardNum());
			}
			
			responseBodyEntity.setData(vo);
			responseBodyEntity.setMsg("");
			responseBodyEntity.setState(Constants.SUCCEED);
		}else{		
			responseBodyEntity.setData("/login");
			responseBodyEntity.setMsg("未发现你的认证信息!为了避免信息泄露!请重新登录!");
			responseBodyEntity.setState(Constants.FAILURE);
			return responseBodyEntity;
		}
		return responseBodyEntity;
	}
 
	// 此方法是POST请求上传的参数中包含本地图片信息File类型
	@ApiOperation("上传营业执照的校验")
	@RequestMapping(value="uploadLiscense",method= {RequestMethod.GET,RequestMethod.POST})
    public ResponseBodyEntity uploadLiscense(String phoneNum, MultipartFile file, String token) throws Exception {
    	ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
    	
    	AgentUser user = userService.findUserByPhone(phoneNum);
		if(user != null && user.getUserId() != null && user.getIsIdentifi() == -1){
			if(!file.isEmpty()){
				
				LicenceImgInfo licence = licenceImgInfoService.findLicenceByUserId(user.getUserId());
				if(licence == null || licence.getLicenceImgId() == null){
					licence = new LicenceImgInfo();
					licence.setCompanyLicenceImg(CosUtil.uploadFile2Cos(file, "licence"));
					licence.setUserId(user.getUserId());
					licence.setStatus(1);
					licence.setCreateTime(DateUtils.getNowDate());
					licence.setCreateUser(user.getNickName());
					licence.setUpdateTime(DateUtils.getNowDate());
					licence.setUpdateUser(user.getNickName());
				}else{
					licence.setCompanyLicenceImg(CosUtil.uploadFile2Cos(file, "licence"));
				}
				licence = licenceImgInfoService.saveLicence(licence);
				licence.setLicenceImgId(-1);
				licence.setUserId(-1);
				responseBodyEntity.setData(licence);
				responseBodyEntity.setMsg("上传营业执照成功!");
				responseBodyEntity.setState(Constants.SUCCEED);
			}else{
				responseBodyEntity.setMsg("请选择营业执照文件!");
				responseBodyEntity.setState(Constants.FAILURE);
				return responseBodyEntity;
			}
		}else{		
			responseBodyEntity.setData("/login");
			responseBodyEntity.setMsg("未发现你的认证信息!为了避免信息泄露!请重新登录!");
			responseBodyEntity.setState(Constants.FAILURE);
			return responseBodyEntity;
		}
    	return responseBodyEntity;
	}
	
	@ApiOperation("查询已经录入的营业执照图片")
	@RequestMapping(value="findLicenceRemime",method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity findLicenceRemime(String phoneNum, String token){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		AgentUser user = userService.findUserByPhone(phoneNum);
		if(user != null && user.getUserId() != null && user.getIsIdentifi() == -1){
			LicenceUserVo vo = new LicenceUserVo();
			
			IdentifiInfo identify = identifiInfoService.findIdentifiInfoByUserId(user.getUserId());
			
			//营业执照
			if(user.getIsBindingLicence() != 1){
				LicenceImgInfo licence = licenceImgInfoService.findLicenceByUserId(user.getUserId());
				if(licence != null && licence.getLicenceImgId() != null){
					vo.setCompanyLicenceImg(licence.getCompanyLicenceImg());
				}
			}else{
				vo.setCompanyLicenceImg(identify.getCompanyLicenceImg());
			}
			vo.setCompanyLicenceCode(identify.getCompanyLicenceCode());
			vo.setCompanyAddress(identify.getCompanyAddress());
			vo.setCompanyName(identify.getCompanyName());
			
			//身份证
			if(user.getIsBindingCard() != 1){
				IdCardInfo card = idCardInfoService.findCardByUserId(user.getUserId());
				if(card != null && card.getIdCardInfoId() != null){
					vo.setUserName(card.getUserName());
					vo.setIdNum(card.getCardNum());
					vo.setAddress(card.getAddress());
					vo.setIdCardImg1(card.getIdCardImg1());
					vo.setIdCardImg2(card.getIdCardImg2());
				}
			}else{
				vo.setUserName(identify.getUserName());
				vo.setIdNum(identify.getIdNum());
				vo.setAddress(identify.getAddress());
				vo.setIdCardImg1(identify.getIdCardImg1());
				vo.setIdCardImg2(identify.getIdCardImg2());
				
				//银行卡
				vo.setPayeeName(identify.getPayeeName());
				vo.setPayeeCardFrom(identify.getPayeeCardFrom());
				vo.setPayeeCardNum(identify.getPayeeCardNum());
			}
			
			responseBodyEntity.setData(vo);
			responseBodyEntity.setMsg("");
			responseBodyEntity.setState(Constants.SUCCEED);
		}else{		
			responseBodyEntity.setData("/login");
			responseBodyEntity.setMsg("未发现你的认证信息!为了避免信息泄露!请重新登录!");
			responseBodyEntity.setState(Constants.FAILURE);
			return responseBodyEntity;
		}
		return responseBodyEntity;
	}
	
	
	
    // 此方法是把传进的字节流转化为相应的字符串并返回，此方法一般在网络请求中用到
    public static String ConvertStreamToString(InputStream is, String charset)
            throws Exception {
        StringBuilder sb = new StringBuilder();
        try (InputStreamReader inputStreamReader = new InputStreamReader(is,charset)) {
            try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\r\n");
                }
            }
        }
        return sb.toString();
    }
    
    /**
     * 20190117 新接口
   	 * 企业/商铺 认证信息提交   
   	 * @return
   	 */
   	@ApiOperation("企业/商铺 认证信息提交     改变状态为审核中")
   	@RequestMapping(value="subCompnyIdentifyInfoAndFinish",method= {RequestMethod.GET,RequestMethod.POST})
   	public ResponseBodyEntity subCompnyIdentifyInfoAndFinish(String phoneNum, String searchCode,String companyAddress,String companyName,String token){
   		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
   		
   		AgentUser user = userService.findUserByPhone(phoneNum);
   		if(user != null && user.getIsIdentifi() == -1){
   			if(searchCode != null && companyAddress != null && companyName != null){
   				IdentifiInfo identify = identifiInfoService.findIdentifiInfoByUserId(user.getUserId());
   				if(identify != null && identify.getUserId() != null){
   					if(identify.getSearchCode().equals(searchCode)){
   						
   						//营业执照
   						identify.setCompanyLicenceImg("营业执照暂不需");
   						
   						//身份证
   						identify.setAddress("身份证暂不需");
						identify.setUserName("身份证暂不需");
						identify.setIdNum("身份证暂不需");
						identify.setIdCardImg1("身份证暂不需");
						identify.setIdCardImg2("身份证暂不需");
   						
   						//基础信息
   						identify.setCompanyAddress(companyAddress);
   						identify.setCompanyLicenceCode("营业证明暂不需");
   						identify.setCompanyName(companyName);
   						identify.setPayeeName("银行卡暂不需");
						identify.setPayeeCardFrom("银行卡暂不需");
						identify.setPayeeCardNum("银行卡暂不需");
						
						user.setIsBindingCard(1);
						user.setIsBindingLicence(1);
						user.setIsBindingBank(1);
						user.setIsIdentifi(user.getRoleId());    //1直接审核通过
						//个体认证完成？
						user = userService.updateUser(user);
						
						identify.setSearchCode("");
						identify.setRoleId(user.getRoleId());
						identify.setStatus(1);     //1直接审核通过
						identify.setUpdateTime(DateUtils.getNowDate());
						identify.setUpdateUser(user.getNickName());
						identify.setRechargeRatio(Constants.RechargeRatioLevel1);     //默认0.01
						identify.setRatioByActivity(Constants.RatioByActivityLevel1);     //附加值默认为0
						identifiInfoService.saveIdentifyInfo(identify);
						
						responseBodyEntity.setData(user);
						responseBodyEntity.setMsg("恭喜商铺认证成功!");
						responseBodyEntity.setState(Constants.SUCCEED);
   					}else{
   						responseBodyEntity.setMsg("短信验证码错误!");
   						responseBodyEntity.setState(Constants.FAILURE);
   						return responseBodyEntity;
   					}
   				}else{
   					responseBodyEntity.setMsg("短信验证码失效!请重新发送短信!");
   					responseBodyEntity.setState(Constants.FAILURE);
   					return responseBodyEntity;
   				}
   			}else{
   				responseBodyEntity.setMsg("信息不能为空!");
   				responseBodyEntity.setState(Constants.FAILURE);
   				return responseBodyEntity;
   			}
   		}else{		
   			responseBodyEntity.setData("/login");
			responseBodyEntity.setMsg("未发现你的认证信息!为了避免信息泄露!请重新登录!");
			responseBodyEntity.setState(Constants.FAILURE);
			return responseBodyEntity;
   		}
   		return responseBodyEntity;
   	}
    
    /**
   	 * 企业/商铺 认证信息提交
   	 * @return
   	 */
   	@ApiOperation("企业/商铺 认证信息提交     改变状态为审核中")
   	@RequestMapping(value="subCompnyIdentifyInfo",method= {RequestMethod.GET,RequestMethod.POST})
   	public ResponseBodyEntity subCompnyIdentifyInfo(String phoneNum, String searchCode,String companyAddress,String companyName,String companyLicenceCode,
   			String payeeName, String payeeCardNum, String payeeCardFrom, String token){
   		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
   		
   		AgentUser user = userService.findUserByPhone(phoneNum);
   		if(user != null && user.getIsIdentifi() == -1){
   			if(searchCode != null && payeeName != null && payeeCardNum != null && payeeCardFrom != null &&
   					companyAddress != null && companyName != null && companyLicenceCode != null){
   				payeeCardNum = payeeCardNum.replace(" ","");
   				companyLicenceCode = companyLicenceCode.replace(" ","");
   				
   				IdentifiInfo identify = identifiInfoService.findIdentifiInfoByUserId(user.getUserId());
   				if(identify != null && identify.getUserId() != null){
   					if(identify.getSearchCode().equals(searchCode)){
   						
   						//营业执照
   						LicenceImgInfo licence = licenceImgInfoService.findLicenceByUserId(user.getUserId());
   						if(licence != null && licence.getLicenceImgId() != null){
   							identify.setCompanyLicenceImg(licence.getCompanyLicenceImg());
   						}else{
   							responseBodyEntity.setMsg("营业执照上传失效!请重新上传!");
   							responseBodyEntity.setState(Constants.FAILURE);
   							return responseBodyEntity;
   						}
   						
   						//身份证
   						IdCardInfo card = idCardInfoService.findCardByUserId(user.getUserId());
   						if(card != null && card.getIdCardInfoId() != null){
   							identify.setAddress(card.getAddress());
   							identify.setUserName(card.getUserName());
   							identify.setIdNum(card.getCardNum());
   							identify.setIdCardImg1(card.getIdCardImg1());
   							identify.setIdCardImg2(card.getIdCardImg2());
   							
   						}else{
   							responseBodyEntity.setMsg("身份证正面照上传失效!请重新上传!");
   							responseBodyEntity.setState(Constants.FAILURE);
   							return responseBodyEntity;
   						}
   						
   						//基础信息
   						identify.setCompanyAddress(companyAddress);
   						identify.setCompanyLicenceCode(companyLicenceCode);
   						identify.setCompanyName(companyName);
   						identify.setPayeeName(payeeName);
						identify.setPayeeCardFrom(payeeCardFrom);
						identify.setPayeeCardNum(payeeCardNum);
						
						user.setIsBindingCard(1);
						user.setIsBindingLicence(1);
						user.setIsBindingBank(1);
//						user.setIsIdentifi(0);    //0审核中         审核通过才改变为1   
						user.setIsIdentifi(user.getRoleId());    //1直接审核通过
						//个体认证完成？
						user = userService.updateUser(user);
						
						identify.setSearchCode("");
						identify.setRoleId(user.getRoleId());
//						identify.setStatus(0);     //审核中
						identify.setStatus(1);     //1直接审核通过
						identify.setUpdateTime(DateUtils.getNowDate());
						identify.setUpdateUser(user.getNickName());
						identify.setRechargeRatio(0.1);     //默认0.01
						identify.setRatioByActivity(0);     //附加值默认为0
						identifiInfoService.saveIdentifyInfo(identify);
						
						responseBodyEntity.setData(user);
//						responseBodyEntity.setMsg("信息已经提交!请耐心等待审核结果!");
						responseBodyEntity.setMsg("恭喜认证成功!");
						responseBodyEntity.setState(Constants.SUCCEED);
   					}else{
   						responseBodyEntity.setMsg("短信验证码错误!");
   						responseBodyEntity.setState(Constants.FAILURE);
   						return responseBodyEntity;
   					}
   				}else{
   					responseBodyEntity.setMsg("短信验证码失效!请重新发送短信!");
   					responseBodyEntity.setState(Constants.FAILURE);
   					return responseBodyEntity;
   				}
   			}else{
   				responseBodyEntity.setMsg("信息不能为空!");
   				responseBodyEntity.setState(Constants.FAILURE);
   				return responseBodyEntity;
   			}
   		}else{		
   			responseBodyEntity.setData("/login");
			responseBodyEntity.setMsg("未发现你的认证信息!为了避免信息泄露!请重新登录!");
			responseBodyEntity.setState(Constants.FAILURE);
			return responseBodyEntity;
   		}
   		return responseBodyEntity;
   	}
    
    /**
	 * 个体认证    提交
	 * @return
	 */
	@ApiOperation("上传个体认证信息的提交     改变状态为审核中")
	@RequestMapping(value="subPersonInfo",method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity subPersonInfo(String phoneNum, String searchCode, String payeeName, String payeeCardNum, String payeeCardFrom, String token){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		AgentUser user = userService.findUserByPhone(phoneNum);
		if(user != null && user.getIsIdentifi() == -1){
			if(searchCode != null && payeeName != null && payeeCardNum != null && payeeCardFrom != null ){
				IdentifiInfo identify = identifiInfoService.findIdentifiInfoByUserId(user.getUserId());
				payeeCardNum = payeeCardNum.replace(" ","");
				
				if(identify != null && identify.getUserId() != null){
					if(identify.getSearchCode().equals(searchCode)){
						IdCardInfo card = idCardInfoService.findCardByUserId(user.getUserId());
						if(card != null && card.getIdCardInfoId() != null){
							identify.setAddress(card.getAddress());
							identify.setUserName(card.getUserName());
							identify.setIdNum(card.getCardNum());
							identify.setIdCardImg1(card.getIdCardImg1());
							identify.setIdCardImg2(card.getIdCardImg2());
							identify.setPayeeName(payeeName);
							identify.setPayeeCardFrom(payeeCardFrom);
							identify.setPayeeCardNum(payeeCardNum);
							
							user.setIsBindingCard(1);
							user.setIsBindingBank(1);
//							user.setIsIdentifi(0);    //0审核中             审核通过才改变为1   
							user.setIsIdentifi(user.getRoleId());    //1审核通过
							
							//个体认证完成？
							user = userService.updateUser(user);
							
							identify.setSearchCode("");
							identify.setRoleId(user.getRoleId());
//							identify.setStatus(0);     //审核中
							identify.setStatus(1);     //审核通过
							identify.setUpdateTime(DateUtils.getNowDate());
							identify.setUpdateUser(user.getNickName());
							identifiInfoService.saveIdentifyInfo(identify);
							
							responseBodyEntity.setData(user);
//							responseBodyEntity.setMsg("信息已经提交!请耐心等待审核结果!");
							responseBodyEntity.setMsg("恭喜认证成功!");
							responseBodyEntity.setState(Constants.SUCCEED);
						}else{
							responseBodyEntity.setMsg("身份证上传信息失效!请重新上传!");
							responseBodyEntity.setState(Constants.FAILURE);
							return responseBodyEntity;
						}
					}else{
						responseBodyEntity.setMsg("短信验证码错误!");
						responseBodyEntity.setState(Constants.FAILURE);
						return responseBodyEntity;
					}
				}else{
					responseBodyEntity.setMsg("短信验证码失效!请重新发送短信!");
					responseBodyEntity.setState(Constants.FAILURE);
					return responseBodyEntity;
				}
			}else{
				responseBodyEntity.setMsg("信息不能为空!");
				responseBodyEntity.setState(Constants.FAILURE);
				return responseBodyEntity;
			}
		}else{		
			responseBodyEntity.setData("/login");
			responseBodyEntity.setMsg("未发现你的认证信息!为了避免信息泄露!请重新登录!");
			responseBodyEntity.setState(Constants.FAILURE);
			return responseBodyEntity;
		}
		return responseBodyEntity;
	}
	
	@ApiOperation("查找认证信息")
	@RequestMapping(value="findIdentifyInfo",method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity findIdentifyInfo(String phoneNum, String token){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		AgentUser user = userService.findUserByPhone(phoneNum);
		if(user != null && user.getUserId() != null){
			IdentifiInfo identify = identifiInfoService.findIdentifiInfoByUserId(user.getUserId());
			if(identify != null && identify.getIdentifiId() != null){
				responseBodyEntity.setData(identify);
				responseBodyEntity.setState(Constants.SUCCEED);
			}else{
				responseBodyEntity.setData("/login");
				responseBodyEntity.setMsg("未发现你的认证信息!为了避免信息泄露!请重新登录!");
				responseBodyEntity.setState(Constants.FAILURE);
				return responseBodyEntity;
			}
		}else{		
			responseBodyEntity.setData("/login");
			responseBodyEntity.setMsg("未发现你的认证信息!为了避免信息泄露!请重新登录!");
			responseBodyEntity.setState(Constants.FAILURE);
			return responseBodyEntity;
		}
		return  responseBodyEntity;
	}
	
	
	@ApiOperation("查找用户充值分成信息")
	@RequestMapping(value="findRechargeData",method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity findRechargeData(String phoneNum,Integer userId, String token){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		AgentUser user = userService.findUserByPhone(phoneNum);
		if(user != null && user.getUserId() != null){
			if(!JWTUtil.verify(token, user.getUserId()+"", user.getLastLoginTime())){
				responseBodyEntity.setData("/login");
				responseBodyEntity.setMsg(" 登录失效! 请重新登录!");
				responseBodyEntity.setState(Constants.FAILURE);
				return responseBodyEntity;
			}
			
			if(user.getIsIdentifi() != null && user.getIsIdentifi() > 0){
				responseBodyEntity.setData(agentRechargeService.findRechargeData(user.getUserId(),userId));
				responseBodyEntity.setState(Constants.SUCCEED);
			}else{
				responseBodyEntity.setData("/login");
				responseBodyEntity.setMsg("未发现你的认证信息! 为了避免信息泄露!请重新登录!");
				responseBodyEntity.setState(Constants.FAILURE);
				return responseBodyEntity;
			}
		}else{		
			responseBodyEntity.setData(userService.updateUser(user));
			responseBodyEntity.setMsg("登陆失效!请刷新界面! 若刷新无效!请重新登录!");
			responseBodyEntity.setState(Constants.FAILURE);
			return responseBodyEntity;
		}
		return  responseBodyEntity;
	}
	
	@ApiOperation("查找用户登录日志")
	@RequestMapping(value="fingLoginList",method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity fingLoginList(String phoneNum,String token){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		AgentUser user = userService.findUserByPhone(phoneNum);
		if(user != null && user.getUserId() != null){
			if(!JWTUtil.verify(token, user.getUserId()+"", user.getLastLoginTime())){
				responseBodyEntity.setData("/login");
				responseBodyEntity.setMsg("登录失效!请重新登录!");
				responseBodyEntity.setState(Constants.FAILURE);
				return responseBodyEntity;
			}
			
			responseBodyEntity.setData(agentLogService.findAgentLogListByType(user.getUserId(), 1));
			responseBodyEntity.setState(Constants.SUCCEED);
		}else{		
			responseBodyEntity.setData("/login");
			responseBodyEntity.setMsg("登录失效!为了避免信息泄露!请重新登录!");
			responseBodyEntity.setState(Constants.FAILURE);
			return responseBodyEntity;
		}
		return  responseBodyEntity;
	}
	
	@Autowired
	private InviteUserInfoService inviteUserInfoService;
	
	@ApiOperation("代理注册页面点击提交")
	@RequestMapping(value="registForBaby",method= {RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody ResponseBodyEntity registForBaby(String phoneNum,String securityCode,String inviteCode,String token){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		if (securityCode == null || securityCode.equals("")) {
			responseBodyEntity.setState(Constants.FAILURE);
			responseBodyEntity.setMsg("验证码不能为空!");
			return responseBodyEntity;
		}
		UserInfo userInfo = userService.findBabyUserByPhone(phoneNum);
		if(!userInfo.getSecurityCode().equals(securityCode)){
			responseBodyEntity.setState(Constants.FAILURE);
			responseBodyEntity.setMsg("验证码错误!");
			return responseBodyEntity;
		}
		
		AgentUserCustom  agent = userService.findByInviteCode(inviteCode);
		
		AgentInviteUserInfo inviteUser = new AgentInviteUserInfo();
		inviteUser.setAgentId(agent.getUserId());         //邀请人           
		inviteUser.setBeInvitedUserId(userInfo.getUserId());  //被邀请人        
		inviteUser.setStatus(1);
		inviteUser.setCreateTime(DateUtils.getNowDate());
		inviteUser.setCreateUser(agent.getNickName());
		if(inviteUserInfoService.saveInviteUserInfo(inviteUser) != -1){
			userInfo.setSecurityCode("");
			userService.updateBabyUser(userInfo);
			
			responseBodyEntity.setData("");
			responseBodyEntity.setState(Constants.SUCCEED);
			responseBodyEntity.setMsg("注册成功!");
		}else{
			responseBodyEntity.setState(Constants.FAILURE);
			responseBodyEntity.setMsg("注册失败!请稍后再试!");
			return responseBodyEntity;
		}
		return responseBodyEntity;
	}
	
//--------------------------------------------------管理端---------------------------------------------------	
	
	/**
	 * 根据昵称列出用户列表
	 * @param nickName
	 * @param pageInfo
	 * @param status
	 * @param token
	 * @param isHavePhone
	 * @param isHaveWechat
	 * @param isShared
	 * @param timeForLogin
	 * @return
	 */
	@ApiOperation("查询用户列表")
	@RequestMapping(value="findUserListByMap",method= {RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody ResponseBodyEntity findUserListByMap(String nickName,PageInfo<AgentUser> pageInfo,String status,String token,
			String isHavePhone,String isHaveWechat,String isShared,String timeForLogin){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		//用户状态
		Integer s = 0;
		if(status != null && !status.equals("")){
			s = Integer.parseInt(status);
		}else{
			s = null;
		}
		
		//邀请状态
		Integer shared = null;
		if(isShared != null && !isShared.equals("")){
			shared = Integer.parseInt(isShared);
		}else{
			shared = null;
		}
		
		//登录状态
		Integer timeStatus = null;
		if(timeForLogin != null && !timeForLogin.equals("")){
			timeStatus = Integer.parseInt(timeForLogin);
		}else{
			timeStatus = null;
		}
		PageInfo<AgentUser> page = userService.findUserListByMap(pageInfo,nickName,s,isHavePhone,isHaveWechat,shared,timeStatus);
		responseBodyEntity.setData(page);
		responseBodyEntity.setMsg("根据条件列出所有用户信息");
		responseBodyEntity.setState(Constants.SUCCEED);
		responseBodyEntity.setToken(token);
		return responseBodyEntity;
	}
}
